#include <string.h> 
#include "mail.h"
#include "serial.h"
#include "disp.h"
#include "rtc.h"
#include "key.h"
#include "manage.h"
#include "BuffFifo.h"

#define TIME_MAIL_INTERVAL 10
unsigned int time_mail; 
unsigned int time_mail_task;

#define MAIL_MAX 10
#define MAIL_BUFF 100

//BUFF_DECL_FIFO(MailMsgBuf,MAIL_BUFF);

sMailBuf MailBuffer[MAIL_MAX];
unsigned char mail_msg_in;
unsigned char mail_msg_out;

unsigned char sleep_activate = FALSE;

void InitMail( void )
{	
	time_mail = TIME_MAIL_INTERVAL;
	time_mail_task = 10;

	mail_msg_in = 0;
	mail_msg_out = 0;
	
}


int SendMailFifo(unsigned char drv, unsigned char act, unsigned char size, char * pbuf)
{	
	unsigned char t = mail_msg_in+1;
	if (t >= MAIL_MAX)
		t = 0;
	if (t == mail_msg_out)	// isFull()		
	{
		printf("MF %d %d\r\n",drv,act);
		return FALSE;
	}

	MailBuffer[mail_msg_in].drv = drv;			
	MailBuffer[mail_msg_in].act = act;
	MailBuffer[mail_msg_in].size = size;
	MailBuffer[mail_msg_in].buf = pbuf;
		
	mail_msg_in = t;	

//	BUFF_INIT_FIFO(MailMsgBuf);
	
	return TRUE;
}

void TimeMail( void )
{
	if(time_mail > 0)
	{
		time_mail--;
		if(time_mail==0)
		{		
			if(time_mail_task>0)
			{
				time_mail_task--;
			}
			time_mail = TIME_MAIL_INTERVAL;
		}
	}
}

void MailSetToSleepMode(unsigned char sleep)
{
	sleep_activate = sleep;
}

void MailTask( void )
{
	unsigned char drv;
	unsigned char act;
	unsigned char size;
	char * pbuf;

	if(time_mail_task==0 || sleep_activate==TRUE)
	{
		time_mail_task = 10;
		
		if( mail_msg_in != mail_msg_out  )
		{
			drv = MailBuffer[mail_msg_out].drv;
			act = MailBuffer[mail_msg_out].act;
			size = MailBuffer[mail_msg_out].size;
			pbuf = MailBuffer[mail_msg_out].buf;		
		
			switch(drv)
			{
				case MANAGE_DEV:
					ManageMail(act,size,pbuf);				
					break;
				case SERIAL_DEV:
					SerialMail(act,size,pbuf);				
					break;
				case DISP_DEV:
					DispMail(act,size,pbuf);
					break;
				case RTC_DEV:
					RTCMail(act,size,pbuf);
					break;
				case KEYIN_DEV:
					KeyInMail(act,size,pbuf);				
					break;
				default:
					break;
			}
			
			if( (mail_msg_out+1) >= MAIL_MAX)
				mail_msg_out = 0;
			else
				mail_msg_out++;
		}
		
	}
}
